<template>
	<div class="problem-page">
		<van-cell-group>
			<div class="task-title-panel"><span class="task-title">基本信息</span></div>

			<van-field readonly label="污染源名称" v-model="formData.pollutionSourceName" />

			<form-item-radio
				:is-view="isView"
				:readonly="true"
				label="问题来源"
				v-model="formData.problemFromCode"
				:option-list="[]"
				dic-key="ZQT_WTZG_WTLY"
			/>

			<form-item-checkbox
				:readonly="true"
				:is-view="isView"
				label="问题涉及"
				v-model="formData.problemReferCodeArr"
				:option-list="[]"
				dic-key="ZQT_WTZG_WTSJ"
			/>

			<van-field readonly label="问题相关信息" type="textarea" v-model="formData.problemInfo" />

			<form-item-date-time :is-view="isView" label="整改期限" v-model="formData.rectifyLimitDate" :min-date="minDate" :max-date="maxDate" />

			<van-field readonly label="发布人" v-model="formData.openUserName" />

			<form-item-progress label="整改进度" :value="formData.progress" :is-view="isView" />
		</van-cell-group>

		<van-cell-group>
			<div class="task-title-panel"><span class="task-title">整改内容</span></div>

			<div v-for="(item, index) in formData.rectifyItem" :key="index" class="rectify-item">
				<van-cell :title="item.rectifyContent">
					<template #right-icon>
						<van-radio-group v-model="formData.rectifyItem[index].rectifyStatus" @change="onChangeSubRadio(index)">
							<van-radio name="0">整改中</van-radio>
							<van-radio name="1">已完成</van-radio>
						</van-radio-group>
					</template>
				</van-cell>
			</div>

			<van-field :readonly="isView" label="上报人员" v-model="formData.fillUser" />
			<form-item-date-time :readonly="true" :is-view="isView" label="上报时间" formatter="YYYY-MM-DD HH:mm:ss" v-model="formData.fillTime" />
			<van-field :readonly="isView" placeholder="请输入" label="整改情况" type="textarea" v-model="formData.rectifyDesc" />
		</van-cell-group>

		<van-cell-group>
			<form-file-upload
				:ywid="formData.id"
				:business-id="formData.id"
				big-type="ZQT_WTZGFJ"
				small-type="FJ"
				v-model="formData.fileData"
				:disabled="isView"
				@uploadFiles="onUploadFiles"
			/>
		</van-cell-group>

		<!-- fixed submit bar similar to 小程序 bottom action -->
		<div v-if="!isView" class="submit-bar">
			<van-button block type="primary" @click="submitBeforeValidate">提交</van-button>
		</div>
	</div>
</template>

<script>
import { ref, reactive, onMounted, readonly } from 'vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import { getProblem, editProblem } from '@/api/problem'
import FormItemRadio from '@/components/form-item-radio'
import FormItemCheckbox from '@/components/form-item-checkbox'
import FormItemDateTime from '@/components/form-item-time/FormItemDateTime.vue'
import FormFileUpload from '@/components/form-file-upload'
import { showToast } from 'vant'
import Schema from 'async-validator'
import transformDesc from '@/validate/transformDesc'
import { DESC_WTZG } from '@/validate/const'
import { useUserStore, useCacheStore } from '../../../stores'

export default {
	name: 'Problem',
	components: {
		FormItemRadio,
		FormItemCheckbox,
		FormItemDateTime,
		FormFileUpload,
		FormItemProgress: () => import('@/components/form-item-progress/FormItemProgress.vue'),
	},
	setup() {
		const route = useRoute()
		const router = useRouter()
		const userStore = useUserStore()
		const isView = ref(false)
		const minDate = ref(dayjs().add(-1, 'day').unix() * 1000)
		const maxDate = ref(dayjs().add(1, 'day').unix() * 1000)
		const formData = reactive({
			id: '',
			pollutionSourceName: '',
			problemFromCode: '',
			problemReferCodeArr: [],
			problemInfo: '',
			rectifyLimitDate: '',
			openUserName: '',
			progress: 0,
			rectifyItem: [],
			fillUser: '',
			fillTime: '',
			rectifyDesc: '',
			fileData: [],
		})

		// helper to read current user display name
		const getUserDisplayName = (user) => {
			if (!user) return ''
			return user.userName || user.username || user.loginName || user.login || ''
		}

		const initData = async (id) => {
			if (!id) {
				// new form defaults
				formData.id = Date.now().toString()
				// try to fill current user info
				formData.fillTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
				return
			}
			const loginRes = await userStore.ensureLogin()
			const uname = getUserDisplayName(loginRes)
			try {
				const res = await getProblem(id)
				if (res.code === '0') {
					Object.assign(formData, res.data)
					if (!formData.fillTime) {
						// ensure fillTime is in correct format
						formData.fillTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
					}
					if (!formData.fillUser) {
						formData.fillUser = uname
					}
					console.log('Loaded formData.fillTime', formData.fillTime)
					console.log('Loaded formData.fillUser', formData.fillUser)
				} else {
					showToast(res.message || '获取失败')
				}
			} catch (e) {
				console.error(e)
				showToast('网络错误')
			}
		}

		const onUploadFiles = (files) => {
			formData.fileData = files
		}

		const onChangeSubRadio = (index) => {
			const rectifyItem = formData.rectifyItem
			const doneItem = rectifyItem.filter((m) => m.rectifyStatus === '1')
			formData.progress = Math.round((doneItem.length / rectifyItem.length) * 100)
		}

		const handleErrors = (errors) => {
			if (errors && errors.length) {
				showToast(errors[0].message)
			}
		}

		const submitBeforeValidate = () => {
			const params = { ...formData }
			console.log('Submitting with params:', params)
			const { desc } = transformDesc(params, DESC_WTZG)
			const validator = new Schema(desc)
			validator.validate(params, (errors, fields) => {
				if (errors) {
					handleErrors(errors)
				} else {
					submit()
				}
			})
		}

		const submit = async () => {
			try {
				const res = await editProblem(formData)
				if (res.code === '0') {
					showToast('操作成功')
					setTimeout(() => router.back(), 800)
				} else {
					showToast(res.message)
				}
			} catch (e) {
				console.error(e)
				showToast('网络错误')
			}
		}

		onMounted(() => {
			const { id, isView: v } = route.query
			isView.value = v === 'true'
			initData(id)
		})

		return { formData, isView, minDate, maxDate, onUploadFiles, submitBeforeValidate, onChangeSubRadio }
	},
}
</script>

<style scoped>
.problem-page {
	padding-bottom: 60px;
}
.rwlb-tmpl-container {
	padding: 10px;
	background: #f3f3f3;
}
.task-title-panel {
	background: #fff;
	padding: 6px;
}
.task-title {
	font-weight: 600;
}
.rectify-item {
	margin-bottom: 6px;
}

.submit-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 12px 16px;
	background: rgba(255, 255, 255, 0.95);
	box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.05);
}
</style>
